-module(packetgenerator).
-export([init/6]).
-include_lib("records.hrl").

%MeanLength : The mean of packet length
%Rate: The rate of the generator for each unit time
%Sources: The sources path for the packet
%InputPid: The first Input Process Id
init(N, MeanLength, Rate, Sources, InputPid, Utils) ->
  Data = generate_random(N, MeanLength),
  run(Data, 0, Rate, InputPid, Sources, Utils)
  .

run([], NewRate, Rate, Pid, Sources, Utils) ->
  receive
    {_, {time_change, _}} ->
      run([], NewRate, Rate, Pid, Sources, Utils);
    {From, finish} ->
      From ! ok,
      run([], NewRate, Rate, Pid, Sources, Utils);
    {From, close}  ->
      From ! close
  end;

run(Data, NewRate, Rate, Pid, Sources, Utils) ->
  receive
    {_, {time_change, _}} ->
      NRate = NewRate + Rate,
      if
        NRate - trunc(NRate)<0.01 ->
          DataSize = round(utils:exp_random(1));
        true ->
          DataSize = 0
      end,
      NewData = tranfer(Data, DataSize, Pid, Sources, Utils),
      run(NewData, NRate, Rate, Pid, Sources, Utils);
    {From, finish} ->
      From ! ok,
      run(Data, NewRate, Rate, Pid, Sources, Utils)
  end
  .

tranfer([], _, _, _,_) ->
  [];

tranfer(Data, 0, _, _,_) ->
  Data;

tranfer([H|T], Rate, Pid, Sources, Utils)->
  Id = utils:get_id(Utils),
  P = #packet{id=Id, sources=Sources, plength=H},
  Pid ! {self(), {packet, P}},
  receive
    {_, rec_ok} ->
      ok
  end,
  tranfer(T, Rate-1, Pid, Sources, Utils).

generate_random(N, Mean) ->
  utils:reset_random(),
  generate_random(N, [] , Mean).

generate_random(0, T, _) ->
  T;

generate_random(N, T, Mean) ->
  Data = round(utils:exp_random(Mean)),
  if
    Data < 0 ->
      NewData = 0;
    true ->
      NewData = Data
  end,
  generate_random(N-1, [NewData|T], Mean).


